<script setup lang="ts">
import { FormInstance, FormRules } from 'element-plus';
import { onMounted, ref } from 'vue';
import { createNonEmptyRule, ModalForm, request, statusSelect } from '../../../utils';

type DictData = {
  dictType?: string
  label?: string
  value?: string
  sort?: number
  theme?: string
  status?: boolean
  remark?: string
}

type Dict = {
  _id: any
  dictName: string
  dictType: string
}

const props = defineProps<{ row?: DictData, dict: Dict }>()

const form = ref<DictData>({})
const formRef = ref<FormInstance>()

const themes: { value: string, label: string }[] = [
  { value: 'default', label: '默认' },
  { value: 'primary', label: '主要' },
  { value: 'success', label: '成功' },
  { value: 'info', label: '信息' },
  { value: 'warning', label: '警告' },
  { value: 'danger', label: '危险' }
]

const rules: FormRules<DictData> = {
  label: createNonEmptyRule('数据标签不能为空'),
  value: createNonEmptyRule('数据值不能为空')
}

onMounted(() => {
  const { row, dict } = props
  const dictFields = { dictType: dict.dictType, dictId: dict._id }
  form.value = row
    ? { ...row, ...dictFields }
    : { status: true, theme: themes[0].value, ...dictFields }
})

defineExpose<ModalForm>({
  validate () {
    return formRef.value?.validate()
  },
  submit () {
    return request.post(`/dict_data/${props.row ? 'update' : 'add'}`, form.value)
  }
})
</script>

<template>
  <ElForm ref="formRef" label-width="6em" :model="form" :rules="rules">
    <ElFormItem label="字典类型">
      <ElInput disabled :model-value="form.dictType" />
    </ElFormItem>
    <ElFormItem label="数据标签" prop="label">
      <ElInput maxlength="30" v-model="form.label" />
    </ElFormItem>
    <ElFormItem label="数据值" prop="value">
      <ElInput maxlength="60"v-model="form.value" />
    </ElFormItem>
    <ElFormItem label="显示排序">
      <ElInputNumber controls-position="right" :min="1" :max="9999" v-model="form.sort" />
    </ElFormItem>
    <ElFormItem label="回显样式">
      <ElSelect v-model="form.theme">
        <ElOption v-for="_ in themes" :key="_.value" :value="_.value" :label="`${_.label}(${_.value})`" />
      </ElSelect>
    </ElFormItem>
    <ElFormItem label="状态">
      <ElRadioGroup v-model="form.status">
        <ElRadio v-for="_ in statusSelect" :value="_.value">{{ _.label }}</ElRadio>
      </ElRadioGroup>
    </ElFormItem>
    <ElFormItem label="备注">
      <ElInput type="textarea" maxlength="200" v-model="form.remark" />
    </ElFormItem>
  </ElForm>
</template>
